﻿using IntelligentGateway.Model;
using IntelligentGateway.Services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Logging;
using System.IO.Pipelines;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Text;
using IntelligentGateway.Tools;
using System.Diagnostics;
using Newtonsoft.Json;

namespace IntelligentGateway.Controllers.api
{
    [Route("api/[controller]")]
    [ApiController]
    public class SetupController : ControllerBase
    {
        IHostEnvironment _env;
        public SetupController(IHostEnvironment hostEnvironment) { this._env = hostEnvironment; }

        [HttpPost]
        [Route("SetProjectSetting")]
        public ResponseMessage SetProjectSetting(ProjectSettings Settings)
        {
            ResponseMessage message = new ResponseMessage();            
            try
            {
                string json = JsonConvert.SerializeObject(Settings);
                try
                {
                    System.IO.File.WriteAllText(_env.ContentRootPath + @"projectsettings.json", json);
                }
                catch (Exception ex)
                {
                    message.errcode = 1;
                    message.errmsg = ex.Message;
                }              
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询网络信息异常";
            }

            return message;
        }
        [HttpPost]
        [Route("GetProjectSetting")]
        public ResponseMessage GetProjectSetting()
        {
            ResponseMessage message = new ResponseMessage();                     
            try
            {
                string json = System.IO.File.ReadAllText(_env.ContentRootPath + @"projectsettings.json");
                ProjectSettings settings =  JsonConvert.DeserializeObject<ProjectSettings>(json);
                message.data = settings;
            }
            catch (Exception ex)
            {
                message.errcode = 1;
                message.errmsg = ex.Message;
            }       
             return message;
        }
        [HttpPost]
        [Route("SetNetInfo")]
        public ResponseMessage SetNetInfo(List<NetInfo> NetInfos)
        {
            ResponseMessage message = new ResponseMessage();
            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                message.errcode = 1;
                message.errmsg = "windows平台,请从界面设置!";
                return message;
            }
            try
            {
                foreach (NetInfo netInfo in NetInfos)
                {
                    string value = string.Empty;
                    string[] array = netInfo.MaskAddress.Replace(" ", "").Split('.');
                    for (int i = 0; i < array.Length; i++)
                    {
                        value += Convert.ToString(Convert.ToInt32(array[i]), 2);
                    }
                    value = value.PadRight(32, '0');

                    string keyWord = "1";
                    int index = 0;
                    int count = 0;
                    while ((index = value.IndexOf(keyWord, index)) != -1)
                    {
                        count++;
                        index = index + keyWord.Length;
                    }
                    netInfo.MaskAddress = count.ToString();
                }
                bool result = UpdateJMNetInfo(NetInfos);
                if (result)
                {
                    message.errcode = 0;
                }
                else
                {
                    message.errcode = 1;
                    message.errmsg = "修改失败";
                }
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询网络信息异常";
            }

            return message;
        }
        [HttpPost]
        [Route("GetNetInfo")]
        public ResponseMessage GetNetInfo()
        {
            ResponseMessage message = new ResponseMessage();
            //if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            //{
            //    message.errcode = 1;
            //    message.errmsg = "windows平台,请从界面设置!";
            //    return message;
            //}
            try
            {                
                SetupServices setupServices = new SetupServices();
                message = setupServices.GetAllNetworkInterface();
            }
            catch
            {
                message.errcode = 1;
                message.errmsg = "查询网络信息异常";
            }

            return message;
        }
        public bool UpdateJMNetInfo(List<NetInfo> NetInfos)
        {
            try
            {
                using (FileStream fileStream = new FileStream("/etc/netplan/01-network-manager-all.yaml", FileMode.Open, FileAccess.Write, FileShare.Write))
                {
                    fileStream.Seek(0, SeekOrigin.Begin);
                    fileStream.SetLength(0);
                    using (StreamWriter streamWriter = new StreamWriter(fileStream))
                    {
                        streamWriter.WriteLine("network:");
                        streamWriter.WriteLine("  version: 2");
                        streamWriter.WriteLine("  ethernets:");
                        foreach (var t in NetInfos)
                        {
                            streamWriter.WriteLine("    " + t.Name + ":");
                            streamWriter.WriteLine("      dhcp4: false");
                            streamWriter.WriteLine("      addresses: [" + t.IPAddress + "/" + t.MaskAddress + "]");
                            streamWriter.WriteLine("      gateway4: " + t.GateWay);
                            streamWriter.WriteLine("      nameservers: ");
                            streamWriter.WriteLine("         addresses: [" + t.DNS + "]");
                            //streamWriter.WriteLine("        - to: 0.0.0.0/0");
                            //streamWriter.WriteLine("          via: " + t.GateWay);
                            //streamWriter.WriteLine("          metric: 150");
                            //streamWriter.WriteLine("      optional: true");
                        }
                        fileStream.Flush();
                        streamWriter.Close();
                    }
                    fileStream.Close();
                }
                RunCommand("netplan apply");
                return true;
            }
            catch
            {
                return false;
            }
        }
        public NetInfo GetJMNetInfo()
        {
            NetInfo netInfo = new NetInfo();
            try
            {
                StreamReader reader = new StreamReader(@"/etc/netplan/01-network-manager-all.yaml", Encoding.Default);
                string theReply = reader.ReadToEnd();
                reader.Close();
                Regex strRegex = new Regex(@"(?<str>([^\w\s]+|\s*)enp1s0:\s*dhcp4: no([\w\W]*))");
                Regex addressRegex = new Regex(@"([^\w\s]+|\s*)addresses:\s*[^\w\s](?<address>\d+.\d+.\d+.\d+/\d+)]\s*");
                Regex gatewayRegex = new Regex(@"(?<gateway>([^\w\s]+|\s*)via:\s*\d+.\d+.\d+.\d+)\s*");
                Regex maskReg = new Regex(@"\d+.\d+.\d+.\d+/(?<mask>\d+)\s*");
                Regex ipRegex = new Regex(@"\s*(?<ip>\d+.\d+.\d+.\d+)\s*");

                MatchCollection strCollection = strRegex.Matches(theReply);

                if (strCollection.Count > 0)
                {
                    string str_value = strCollection[0].Groups["str"].Value;
                    MatchCollection addressCollection = addressRegex.Matches(str_value);
                    MatchCollection routerCollection = gatewayRegex.Matches(str_value);
                    for (int i = 0; i < addressCollection.Count; i++)
                    {
                        string str = addressCollection[i].Groups["address"].Value.Trim();
                        string ip = ipRegex.Matches(str)[0].Groups["ip"].Value.Trim();
                        netInfo.IPAddress = ip;
                        int mask = Convert.ToInt32(maskReg.Matches(str)[0].Groups["mask"].Value.Trim());
                        string Mask = GetMask(mask);
                        netInfo.MaskAddress = Mask;
                    }

                    for (int i = 0; i < routerCollection.Count; i++)
                    {
                        string str = routerCollection[i].Groups["gateway"].Value.Trim();
                        string ip = ipRegex.Matches(str)[0].Groups["ip"].Value.Trim();
                        netInfo.GateWay = ip;
                    }
                }

                return netInfo;
            }
            catch (Exception ex)
            {
                Log.Debug(ex.ToString());
                return netInfo;
            }
        }
        public string GetMask(int value)
        {
            try
            {
                string str = string.Empty;
                for (int i = 0; i < value; i++)
                {
                    str += "1";
                }
                str = str.PadRight(32, '0');
                string a = Convert.ToInt32(str.Substring(0, 8), 2).ToString() + "." + Convert.ToInt32(str.Substring(8, 8), 2).ToString() + "." + Convert.ToInt32(str.Substring(16, 8), 2).ToString() + "." + Convert.ToInt32(str.Substring(24, 8), 2).ToString();
                return a;
            }
            catch
            {
                return "0.0.0.0";
            }
        }
        public void RunCommand(string command)
        {
            Process.Start("sudo", command);
        }
    }

}
